﻿using System;
using System.Net;
using System.Windows.Forms;
using EIS.ClientUtility.Properties;
using EIS.Data;

namespace EIS.ClientUtility
{
    public partial class LogonView : UserControl
    {
        public LogonView()
        {
            InitializeComponent();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            //Update Client Config First
            try
            {
                var logonInfo = ClientConfig.Instance.LogonInfo;
                logonInfo.UserName = tbUserName.Text;
                logonInfo.Password = tbPassword.Text;
                logonInfo.StoreUsername = checkBoxSaveUserName.Checked;
                logonInfo.StorePassword = checkBoxSavePassword.Checked;
                ClientConfig.Instance.UpdateConfig();

                LogonData logonData = new LogonData();
                var userLogonResponse =logonData.Logon(logonInfo.UserName, logonInfo.Password);

                if (userLogonResponse.Succeed.ToUpper() != "Y")
                {
                    ShowErrorMessageBox.Show( "Incorrect credentials. \nPlease check your username and password");
                }
                else
                {
                    this.Parent.FindForm().Close();
                }
               
            }
            catch (WebException ex)
            {
                string message = ResourceStandard.ConnectionErrorMsg;
                ShowErrorMessageBox.Show(message);

            }

        }

        private void checkBoxSaveUserName_CheckedChanged(object sender, EventArgs e)
        {
            if (!checkBoxSaveUserName.Checked)
            {
                checkBoxSavePassword.Checked = false;
                checkBoxSavePassword.Enabled = false;
            }
            else
            {
                checkBoxSavePassword.Enabled = true;

            }

        }

        private void LogonView_Load(object sender, EventArgs e)
        {
            var logonInfo = ClientConfig.Instance.LogonInfo;

            checkBoxSaveUserName.Checked = logonInfo.StoreUsername;
            checkBoxSavePassword.Checked = logonInfo.StorePassword;

            if (checkBoxSaveUserName.Checked)
            {
                tbUserName.Text = logonInfo.UserName;

            }
            if (checkBoxSavePassword.Checked)
            {
                tbPassword.Text = logonInfo.Password;

            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Parent.FindForm().Close();
        }
    }
}
